package study.mybatis.multi.datasource.support.transaction;

import org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator;
import org.springframework.context.annotation.Bean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.interceptor.TransactionInterceptor;

import java.util.Properties;

/**
 * 事务配置
 *
 * @author wangzhj
 */
//@Configuration
//@EnableTransactionManagement
public class TransactionProxyCfg {

    /* 事务拦截器名称 */
    private static final String TRANSACTION_INTERCEPTOR_NAME = "transactionInterceptor";
    /* 事务Bean名称 */
    private static final String[] TRANSACTION_BEAN_NAMES = {"*ServiceImpl"};

    /**
     * 事务拦截器
     */
    @Bean(TRANSACTION_INTERCEPTOR_NAME)
    public TransactionInterceptor transactionInterceptor(PlatformTransactionManager transactionManager) {
        TransactionInterceptor transactionInterceptor = new TransactionInterceptor();
        //事务管理器
        transactionInterceptor.setTransactionManager(transactionManager);
        //事务属性
        Properties transactionAttributes = new Properties();
        transactionAttributes.setProperty("*", "PROPAGATION_REQUIRED");
        transactionInterceptor.setTransactionAttributes(transactionAttributes);
        return transactionInterceptor;
    }

    /**
     * 自动代理
     *
     * @return BeanNameAutoProxyCreator
     */
    @Bean
    public BeanNameAutoProxyCreator transactionBeanNameAutoProxyCreator() {
        BeanNameAutoProxyCreator transactionAutoProxy = new BeanNameAutoProxyCreator();
        //
        transactionAutoProxy.setProxyTargetClass(true);
        //代理Bean名称
        transactionAutoProxy.setBeanNames(TRANSACTION_BEAN_NAMES);
        //拦截器
        transactionAutoProxy.setInterceptorNames(TRANSACTION_INTERCEPTOR_NAME);
        return transactionAutoProxy;
    }

    /*private RuleBasedTransactionAttribute required() {
        RuleBasedTransactionAttribute required = new RuleBasedTransactionAttribute();
        required.setRollbackRules(Collections.singletbbbbbbbbbbbbbonList(new RollbackRuleAttribute(Exception.class)));
        required.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        required.setTimeout(TransactionDefinition.TIMEOUT_DEFAULT);
        return required;
    }

    private RuleBasedTransactionAttribute readOnly() {
        RuleBasedTransactionAttribute readOnly = new RuleBasedTransactionAttribute();
        readOnly.setReadOnly(true);
        readOnly.setPropagationBehavior(TransactionDefinition.PROPAGATION_NOT_SUPPORTED);
        return readOnly;
    }*/
}
